package com.cjy.action;

import com.cjy.pojo.Book;
import com.cjy.pojo.Page;
import com.cjy.pojo.User;
import com.cjy.service.inter.bookService;
import com.cjy.service.serviceImpl.bookServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "BookAction", urlPatterns = "/BookAction")
public class BookAction extends HttpServlet {
    bookService bookService = new bookServiceImpl();
    Page page = new Page();
    String sel = null;
    String input = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        req.setCharacterEncoding("utf-8");  // 处理网页提交的中文

        String hidden = req.getParameter("hidden");
        if ("login".equals(hidden)) {
            User user = login(req, resp);

            if (bookService.login(user)) {
                out.println("<script>location='index.jsp'</script>");
            } else {
                out.println("<script>alert('登录失败');location='login.jsp'</script>");
            }
        }

        if ("register".equals(hidden)) {
            if (confirmPwd(req, resp)) {
                if (register(req, resp)) {
                    out.println("<script>alert('注册成功');location='login.jsp'</script>");
                } else {
                    out.println("<script>alert('注册失败');location='register.jsp'</script>");
                }
            } else {
                out.println("<script>alert('密码和确认密码不符，请重新输入！');location='register.jsp'</script>");
            }
        }

        if ("insert".equals(hidden)) {
            if (insert(req, resp)) {
                out.println("<script>alert('插入成功');location='index.jsp'</script>");
            } else {
                out.println("<script>alert('插入失败');location='insert.jsp'</script>");
            }
        }

        if ("bookList".equals(hidden)) {
            judge(req, resp);

            List<Book> bookList = page.getBooks();
            if (bookList.size() > 0) {
                req.setAttribute("hidden", "bookList");
                req.setAttribute("page", page);
                req.setAttribute("bookList", bookList);
                req.getRequestDispatcher("bookList.jsp").forward(req, resp);
            } else {
                out.println("<script>alert('列表无数据');location='index.jsp'</script>");
            }
        }

        if ("search".equals(hidden)) {
            if (req.getParameter("input") != null) {
                sel = req.getParameter("sel");
                input = req.getParameter("input");
            }

            judge(req, resp, sel, input);

            List<Book> bookList = page.getBooks();
            if (bookList.size() > 0) {
                req.setAttribute("hidden", "search");
                req.setAttribute("page", page);
                req.setAttribute("bookList", bookList);
                req.getRequestDispatcher("bookList.jsp").forward(req, resp);
            } else {
                out.println("<script>alert('列表无数据');location='bookList.jsp'</script>");
            }
        }

        if ("delete".equals(hidden)) {
            if (bookService.deleteBook(Integer.parseInt(req.getParameter("id"))) > 0) {
                out.println("<script>location='BookAction?hidden=bookList'</script>");
            } else {
                out.println("<script>alert='删除失败';location='BookAction?hidden=bookList'</script>");
            }
        }

        if ("findId".equals(hidden)) {
            Book book = bookService.selectBook(Integer.parseInt(req.getParameter("id")));

            if (book != null) {
                req.setAttribute("book", book);
                req.getRequestDispatcher("update.jsp").forward(req, resp);
            } else {
                out.println("<script>alert('未找到该元素');location='BookAction?hidden=bookList'</script>");
            }
        }

        if ("update".equals(hidden)) {
            Book book = new Book();
            book.setId(Integer.parseInt(req.getParameter("id")));
            book.setIsbn(req.getParameter("isbn"));
            book.setName(req.getParameter("name"));
            book.setPrice(req.getParameter("price"));
            book.setPress(req.getParameter("press"));

            if (bookService.updateBook(book) > 0) {
                out.println("<script>location='BookAction?hidden=bookList'</script>");
            } else {
                out.println("<script>alert('修改失败');location='BookAction?hidden=bookList'</script>");
            }
        }
    }

    private User login(HttpServletRequest req, HttpServletResponse resp) {
        User user = new User();
        user.setUsername(req.getParameter("name"));
        user.setPassword(req.getParameter("pwd"));

        return user;
    }

    private boolean confirmPwd(HttpServletRequest req, HttpServletResponse resp) {
        String pwd = req.getParameter("pwd");
        String con_pwd = req.getParameter("con_pwd");

        if (pwd.equals(con_pwd)) {
            return true;
        } else {
            return false;
        }
    }

    private boolean register(HttpServletRequest req, HttpServletResponse resp) {
        User user = new User();
        user.setUsername(req.getParameter("name"));
        user.setPassword(req.getParameter("pwd"));

        if (bookService.register(user) != 0) {
            return true;
        } else {
            return false;
        }
    }

    private boolean insert(HttpServletRequest req, HttpServletResponse resp) {
        Book book = new Book();
        book.setIsbn(req.getParameter("isbn"));
        book.setName(req.getParameter("name"));
        book.setPrice(req.getParameter("price"));
        book.setPress(req.getParameter("press"));

        if (bookService.insertBook(book) != 0) {
            return true;
        } else {
            return false;
        }
    }

    private void judge(HttpServletRequest req, HttpServletResponse resp) {
        String current = req.getParameter("cur");

        if (current == null) {
            page.setPage(0, 5);
        } else {
            if (page.getCurrentPage() > Integer.parseInt(current) && Integer.parseInt(current) > 0) {
                page.setCurrentNum(page.getCurrentNum() - page.getPageSize());
                page.setCurrentPage(Integer.parseInt(current));
            } else if (page.getCurrentPage() < Integer.parseInt(current) && Integer.parseInt(current) <= page.getTotalPage()){
                page.setCurrentNum(page.getCurrentNum() + page.getPageSize());
                page.setCurrentPage(Integer.parseInt(current));
            } else {
                page.setCurrentPage(page.getCurrentPage());
            }
        }

        List<Book> List = bookService.selectBook();
        page.setBooks(bookService.selectBook(page));

        if (List.size() % page.getPageSize() == 0) {
            page.setTotalPage(List.size() / page.getPageSize());
        } else {
            page.setTotalPage((List.size() / page.getPageSize()) + 1);
        }
    }

    private void judge(HttpServletRequest req, HttpServletResponse resp, String sel, String input) {
        String current = req.getParameter("cur");

        if (current == null) {
            page.setPage(0, 5);
        } else {
            if (page.getCurrentPage() > Integer.parseInt(current) && Integer.parseInt(current) > 0) {
                page.setCurrentNum(page.getCurrentNum() - page.getPageSize());
                page.setCurrentPage(Integer.parseInt(current));
            } else if (page.getCurrentPage() < Integer.parseInt(current) && Integer.parseInt(current) <= page.getTotalPage()){
                page.setCurrentNum(page.getCurrentNum() + page.getPageSize());
                page.setCurrentPage(Integer.parseInt(current));
            } else {
                page.setCurrentPage(page.getCurrentPage());
            }
        }

        List<Book> List = bookService.selectBook(sel, input);
        page.setBooks(bookService.selectBook(sel, input, page));

        if (List.size() % page.getPageSize() == 0) {
            page.setTotalPage(List.size() / page.getPageSize());
        } else {
            page.setTotalPage((List.size() / page.getPageSize()) + 1);
        }
    }
}
